﻿package {
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.external.ExternalInterface;

	public class SocketConnection {
	
		private var socket:Socket;
		
		public function SocketConnection( host: String, port:Number ) {
			socket = new Socket(  );         
			socket.addEventListener( ProgressEvent.SOCKET_DATA, onDataReceived );	  
			socket.connect( host, port );
		}
		
		public function onDataSend(data: String):void {
			socket.addEventListener( ProgressEvent.SOCKET_DATA, onDataReceived );	  
			socket.writeUTFBytes(data + "\n");
			socket.flush();
		}

		private function onDataReceived( event:ProgressEvent ):void {        
			if (socket.bytesAvailable>0) { 
				var datas:String = socket.readUTFBytes(socket.bytesAvailable); 
				if (ExternalInterface.available)
					ExternalInterface.call("on_data_received", datas);
			}
		}
	}
}